import 'dart:typed_data';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:photo_pipeline/photo_pipeline.dart';

import '../providers/pipeline_providers.dart';

/// 缩略图展示组件：通过 controller.camera.getThumbnailFile 获取缓存字节。
class Base64CachedImage extends ConsumerStatefulWidget {
  const Base64CachedImage({
    super.key,
    required this.fileInfo,
    this.width,
    this.height,
    this.fit,
    this.filterQuality = FilterQuality.low,
    this.gaplessPlayback = true,
    this.placeholder,
    this.errorWidget,
    this.refresh = false,
  });

  final FileInfo fileInfo;
  final double? width;
  final double? height;
  final BoxFit? fit;
  final FilterQuality filterQuality;
  final bool gaplessPlayback;
  final Widget? placeholder;
  final Widget? errorWidget;
  final bool refresh;

  @override
  ConsumerState<Base64CachedImage> createState() => _Base64CachedImageState();
}

class _Base64CachedImageState extends ConsumerState<Base64CachedImage> {
  late Future<Uint8List> _future;

  @override
  void initState() {
    super.initState();
    _future = _load();
  }

  @override
  void didUpdateWidget(covariant Base64CachedImage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.fileInfo.id != widget.fileInfo.id ||
        oldWidget.refresh != widget.refresh) {
      _future = _load();
    }
  }

  Future<Uint8List> _load() async {
    final controller = ref.read(pipelineControllerProvider);
    final stopwatch = Stopwatch()..start();
    try {
      final bytes = await controller.camera.getThumbnailFile(
        widget.fileInfo,
        refresh: widget.refresh,
      );
      stopwatch.stop();
      debugPrint(
        '[HomeScreen] 缩略图加载完成 id=${widget.fileInfo.id} '
        '耗时=${stopwatch.elapsedMilliseconds}ms',
      );
      return bytes;
    } catch (error) {
      stopwatch.stop();
      debugPrint(
        '[HomeScreen] 缩略图加载失败 id=${widget.fileInfo.id} error=$error',
      );
      rethrow;
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<Uint8List>(
      future: _future,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return widget.placeholder ?? const _DefaultPlaceholder();
        }

        if (snapshot.hasError || !snapshot.hasData) {
          return widget.errorWidget ?? _DefaultErrorWidget();
        }

        final bytes = snapshot.data!;
        return Image.memory(
          bytes,
          width: widget.width,
          height: widget.height,
          fit: widget.fit,
          filterQuality: widget.filterQuality,
          gaplessPlayback: widget.gaplessPlayback,
          errorBuilder: (context, error, stackTrace) {
            return widget.errorWidget ?? _DefaultErrorWidget();
          },
        );
      },
    );
  }
}

class _DefaultPlaceholder extends StatelessWidget {
  const _DefaultPlaceholder();

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: SizedBox(
        width: 16,
        height: 16,
        child: CircularProgressIndicator(strokeWidth: 2),
      ),
    );
  }
}

class _DefaultErrorWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const Center(
      child: Icon(
        Icons.broken_image_outlined,
        size: 24,
        color: Colors.grey,
      ),
    );
  }
}
